<?php

Yii::import('application.vendors.facebook-php-sdk.Facebook');
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'SocialProvider.php');
class FacebookProvider extends SocialProvider
{
    public $type = 'facebook';
    public $useProxy=false;
    
    private $_facebook;
    
    public function authenticate()
    {
        if ($this->_facebook === null)
        {
            // Create our Application instance (replace this with your appId and secret).
            $this->_facebook = new Facebook(array(
                'appId'  => $this->server['appId'],
                'secret' => $this->server['secret'],
            ));
            
            if ($this->useProxy)
            {
                // proxy server
                Facebook::$CURL_OPTS[CURLOPT_HTTPPROXYTUNNEL] = 1;
                Facebook::$CURL_OPTS[CURLOPT_PROXY] = '127.0.0.1';
                Facebook::$CURL_OPTS[CURLOPT_PROXYPORT] = '9666';
            }
            Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;

            // Get User ID
            $user = $this->_facebook->getUser();

            // We may or may not have this data based on whether the user is logged in.
            //
            // If we have a $user id here, it means we know the user is logged into
            // Facebook, but we don't know if the access token is valid. An access
            // token is invalid if the user logged out of Facebook.

            if ($user) {
                try {
                    // Proceed knowing you have a logged in user who's authenticated.
                    $user_profile = $this->_facebook->api('/me');
                } catch (FacebookApiException $e) {
                    Yii::log($e->getMessage(), CLogger::LEVEL_ERROR);
                    $user = null;
                }
            }

            // Login or logout url will be needed depending on current user state.
            if ($user) {
                //$logoutUrl = $facebook->getLogoutUrl();
                // This call will always work since we are fetching public data.
                return $this->_facebook;
            } else {
                $loginUrl = $this->_facebook->getLoginUrl();
                Yii::app()->controller->redirect($loginUrl);
            }
        }
        return false;
    }
}